<template>
    <el-dialog class="upload-work" draggable align-center :title="dialogTile" v-model="dialogVisible" @close="closeDialog"
        width="800">
        <el-form :model="userForm" :rules="userRules" ref="userFormRef">
            <el-form-item label="头像：" label-width="120" prop="profilePath">
                <el-upload ref="uploadPic" class="avatar-uploader" :action="uploadFileUrl" methods="post"
                    :before-upload="beforePicUpload" :on-preview="handlePreview" :on-success="handleSuccess"
                    :on-error="handleError" :limit="1" :on-exceed="handlePicExceed" :auto-upload="false"
                    :file-list="picFileList" list-type="picture-card" :headers="{
                        'Authorization': 'Bearer ' + token
                    }">
                    <template #trigger>
                        <el-button size="small" type="primary">选择文件</el-button>
                    </template>
                    <el-button type="success" class="submit-bt" @click="submitUpload(userFormRef)">点击上传</el-button>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="saveWork(userFormRef)">保存</el-button>
        </template>
    </el-dialog>
    <el-dialog v-model="picDialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
</template>
<script setup>
import { ref } from 'vue';
import { uploadFileUrl, PutUserInfo } from '@/api/front/contest'
import { ElMessage, genFileId } from 'element-plus';
import store from '@/store';

const dialogVisible = ref(false)
const picDialogVisible = ref(false)
const dialogImageUrl = ref('')
const uploadPic = ref('')
const token = window.localStorage.getItem('userInfo').token
const userFormRef = ref()

const userInfo = store.state.userInfo
const userForm = ref(
    {
        userId: userInfo.userId,
        synopsis: userInfo.synopsis,
        phone: userInfo.phone,
        profilePath: userInfo.avatar,
        // username: userInfo.username,
        nickName: userInfo.nickname
    }
)
const userRules = ref({
    // 作品验证
    profilePath: [
        { required: true, message: '请上传头像', trigger: 'change' }
    ]
})
const picFileList = ref([])

const openDialog = async () => {
    dialogVisible.value = true
}
const closeDialog = () => {
    dialogVisible.value = false
    // 初始化表单
    userForm.value = {
        userId: userInfo.userId,
        synopsis: userInfo.synopsis,
        phone: userInfo.phone,
        profilePath: '',
        username: userInfo.username,
        nickname: userInfo.nickname,
    }
    picFileList.value = []
}

const beforePicUpload = (file) => {
    const isJPG = file.type === 'image/jpeg'
    const isPNG = file.type === 'image/png'
    const isLt3M = file.size / 1024 / 1024 < 3
    if (!isJPG && !isPNG) {
        ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!')
        return false
    }
    if (!isLt3M) {
        ElMessage.error('上传头像图片大小不能超过 3MB!')
        return false
    }
    return true
}

const handlePreview = (file) => {
    console.log(file)
    dialogImageUrl.value = file.url
    picDialogVisible.value = true
}
const handleError = (err) => {
    console.log(err)
}
const handlePicExceed = (files) => {
    // 用JS写upload.value!.clearFiles()
    uploadPic.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadPic.value.handleStart(file)
}
const handleSuccess = (res, file) => {
    console.log(res)
    console.log(file)
    if (file.status == 'success') {
        ElMessage.success('上传成功')
        if (file.raw.type == 'image/png' || file.raw.type == 'image/jpeg') {
            userForm.value.profilePath = res
        } else {
            userForm.value.workPath = res
        }
    }
    console.log(userForm.value)
}

// 判断是否点击上传按钮
const isClick = ref(null)
const submitUpload = async (formRef) => {
    if (!formRef) {
        return
    }
    await formRef.validate(async (valid, fields) => {
        if (valid) {
            isClick.value = true
            console.log('isClick');
            uploadPic.value.submit()
        } else {
            console.log('error submit!', fields);
        }
    });
}

const saveWork = async (formRef) => {
    if (!formRef) {
        return
    }
    await formRef.validate(async (valid, fields) => {
        if (valid && isClick.value == true) {
            console.log('submit!');
            // 上传作品
            console.log('userForm.value', userForm.value)
            const res = await PutUserInfo(userForm.value)
            console.log('res', res)
            if (res.data == '修改成功') {
                ElMessage.success('上传成功')
                const newUserInfo = {
                    userId: userInfo.userId,
                    roleId: userInfo.roleId,
                    role: userInfo.role,
                    username: userInfo.username,
                    nickname: userInfo.nickname,
                    phone: userInfo.phone,
                    avatar: userForm.value.profilePath,
                    synopsis: userInfo.synopsis,
                    academy: userInfo.academy,
                    token: userInfo.token,
                }
                store.commit('setUserInfo', newUserInfo);
                localStorage.userInfo = JSON.stringify(newUserInfo);
                closeDialog()
            } else {
                ElMessage.error('上传失败')
            }
        } else {
            ElMessage.error('未点击上传')
            console.log('error submit!', fields);
        }
    });
}

defineExpose({
    openDialog,
    saveWork
})
</script>
<style lang="scss" scoped>
.upload-work {
    .submit-bt {
        margin-left: 10px;
        float: inline-end;
        // height: 30px;
        // width: 70px;
        // font-size: 12px;
        // font-weight: normal;
        // border-radius: 5px;
    }

    .video {
        width: 100%;
        height: 300px;
    }
}
</style>